<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\QrCodeController;
use App\Models\CodeGuideProduction;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 展览配置类
 */
class CodeGuideExhibitionController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\CodeGuideExhibition();
        $this->validate = new  \App\Validate\CodeGuideExhibitionValidate();
    }

    /**
     * 列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     * @param is_play string 是否发布  1 发布  2 未发布
     * @param create_start_time datetime 展览创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 展览创建结束时间
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $create_start_time = $this->request->create_start_time;
        $create_end_time = $this->request->create_end_time;
        $is_play = $this->request->is_play;

        $res = $this->model->lists(null, $keywords, $is_play, null, $create_start_time, $create_end_time, $limit);
        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        //获取作品数量
        $productionModel = new CodeGuideProduction();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['intro'] =  strip_tags($val['intro']);
            $res['data'][$key]['production_num'] = $productionModel->getProductionNum($val['id']);
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 展览id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;

        $res = $this->model->detail($id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param name string 展览名
     * @param img string 图片
     * @param start_time string 展览开始时间
     * @param end_time string 展览结束时间
     * @param intro string 简介
    // * @param is_play string 是否发布  1 发布  2 未发布
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->name, 'name');
        if ($is_exists) {
            return $this->returnApi(202, "该展览名称已存在");
        }

        $qrCodeObj = new QrCodeController();
        $qr_code = $qrCodeObj->getQrCode('code_guide_exhibition');
        if ($qr_code === false) {
            Log::error("扫码导游展览二维码生成失败,请手动生成");
            return $this->returnApi(201, "添加失败，请重新添加");
        }
        //生成二维码
        $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pCodeNav/list/index?from=code_guide_exhibition&token=' . $qr_code;
        $qr_url = $qrCodeObj->setQr($qr_data, true, 300, 1, [0, 0, 0]);

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'name' => $this->request->name,
                'img' => $this->request->img ? $this->request->img : 'default/default_code_guide_exhibition.png',
                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'intro' => $this->request->intro,
                //       'is_play' => $this->request->is_play,
                'qr_code' => $qr_code,
                'qr_url' => $qr_url,
                'manage_id' => $this->request->manage_id,
            ];
            $this->model->add($data);

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "添加成功", true);
        } catch (\Exception $e) {
            //   var_dump($e->getMessage());exit;
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "添加失败" . $e->getMessage());
        }
    }



    /**
     * 编辑
     * @param id int 展览id
     * @param name string 展览名
     * @param img string 图片
     * @param start_time string 展览开始时间
     * @param end_time string 展览结束时间
     * @param intro string 简介
  //   * @param is_play string is_play
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->name, 'name', $this->request->id);

        if ($is_exists) {
            return $this->returnApi(202, "该展览名称已存在");
        }

        $id = $this->request->id;
        $res = $this->model->detail($id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        $old_img = $res->img;

        // 启动事务
        DB::beginTransaction();
        try {

            $data = [
                'id' => $this->request->id,
                'name' => $this->request->name,
                'img' => $this->request->img ? $this->request->img : 'default/default_code_guide_exhibition.png',
                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'intro' => $this->request->intro,
                //   'is_play' => $this->request->is_play
            ];

            if (empty($res['qr_url'])) {
                //生成二维码
                $qrCodeObj = new QrCodeController();
                if (empty($res['qr_code'])) {
                    $qr_code = $qrCodeObj->getQrCode('code_guide_exhibition');
                    if ($qr_code === false) {
                        Log::error("扫码导游展览二维码生成失败,请手动生成");
                        throw new Exception("二维码生成失败");
                    }
                } else {
                    $qr_code = $res['qr_code'];
                }
                //生成二维码
                $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pCodeNav/list/index?from=code_guide_exhibition&token=' . $qr_code;
                $qr_url = $qrCodeObj->setQr($qr_data, true, 300, 1, [0, 0, 0]);
                $data['qr_url'] = $qr_url;
                $data['qr_code'] = $qr_code;
            }
            $this->model->change($data);

            //删除旧资源
            if ($old_img != $this->request->img && $old_img != 'default/default_code_guide_exhibition.png') {
                $this->deleteFile($old_img);
            }
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 展览id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $productionModel = new CodeGuideProduction();
        $production_number = $productionModel->getProductionNum($this->request->id);
        if (!empty($production_number)) {
            return $this->returnApi(202, "此展览已有作品，不允许删除，如需删除，请先删除展览下的作品!");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }


    /**
     * 撤销 和发布
     * @param id int 活动id
     * @param is_play int 发布   1 发布  2 撤销
     */
    public function cancelAndRelease()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_and_release')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断是否符合发布的条件
        if ($this->request->is_play == 1) {
            $productionModel = new CodeGuideProduction();
            $production_number = $productionModel->getProductionNum($this->request->id);
            if (empty($production_number)) {
                return $this->returnApi(202, '当前展览下没有作品，暂不允许发布！');
            }
        }

        DB::beginTransaction();
        try {
            list($code, $msg) = $this->model->resumeAndCancel($this->request->id, 'is_play', $this->request->is_play);

            $is_play = $this->request->is_play == 1 ? '发布' : '撤销';

            DB::commit();
            return $this->returnApi($code, $is_play . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
